package org.gdpu.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.gdpu.model.Person;
import org.gdpu.model.Resource;
import org.gdpu.model.Valid;
import org.gdpu.service.ResourceService;
import org.gdpu.service.impl.ResourceServiceImpl;
import org.gdpu.util.ChangeTime;
import org.gdpu.util.fileConverter.FileUtils;
import org.gdpu.vo.ResourceVO;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-6-5
 * Time: 下午9:48
 * To change this template use File | Settings | File Templates.
 */

//文件下载
@Component("FileDownload")
@Scope("prototype")
public class FileDownloadAction extends ActionSupport implements ModelDriven<ResourceVO> {

    private ResourceService resourceService;
    private final ResourceVO resourceVO = new ResourceVO();
    private Logger logger = LogManager.getLogger(FileDownloadAction.class.getName());
    private static Process process;//执行子进程

    //返回一个输入流，作为一个客户端来说是一个输入流，但对于服务器端是一个 输出流
    public InputStream getDownloadFile() throws Exception {

        if (resourceVO.getFlag() != 1) {
            Resource resource = resourceService.find(Resource.class, Integer.valueOf(resourceVO.getResourceId()));
            resourceVO.setFileName(new String(resource.getFileName().getBytes(), "ISO8859-1"));
            File file = new File(resourceVO.getFilePath());
            if (file.exists()) {
                resourceService.updateDownloadTime(Integer.valueOf(resourceVO.getResourceId()));
                return new FileInputStream(file);
            } else {
                resourceVO.setResultMessage("找不到该资源，或该资源已被删除！");
                return null;
            }
        } else {
            resourceVO.setFileName(new String((ChangeTime.formatDate(new Date()) + ".doc").getBytes(), "ISO8859-1"));
            File file = new File(resourceVO.getFilePath());
            return new FileInputStream(file);
        }
    }

    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }

    //在线预览
    public String watch() {
        Resource resource = resourceService.find(Resource.class, Integer.valueOf(resourceVO.getResourceId()));
        if (resource.getResourceCategory().getName().equals("视频")) {
            resourceVO.setFilePath(resource.getFilePath());
            return "video";
        }
        if (resource.getResourceCategory().getName().equals("案例")) {

        }
        if (resource.getResourceCategory().getName().equals("课件") ||
                FileUtils.isSufix(FileUtils.getFileSufix(resource.getFileName()), "pdf,txt")) {
            String fileName = FileUtils.getFilePrefix(FileUtils.getRealFileName(resource.getFilePath())) + ".swf";
            resourceVO.setFileName(ResourceServiceImpl.SWF_PATH_DIR + fileName);
            return "preview";
        }
        return ERROR;
    }

    //查询资源

    public String search() {
        List<Resource> resources = resourceService.findResourceByFileName(resourceVO.getSearch());
        if (resources == null) {
            resourceVO.setResultMessage("找不到相关资源!");
            return ERROR;
        }
        for (Resource r : resources)
            r.setFileName(r.getFileName().substring(0, r.getFileName().trim().lastIndexOf(".")));
        resourceVO.setResources(resources);
        return "search";
    }

    //根据分类查询资源
    public String searchCategory() {
        List<Resource> resources = resourceService.findResourceByCategory(resourceVO.getResourceCategory());
        if (resources == null) {
            resourceVO.setResultMessage("找不到相关资源!");
            return ERROR;
        }
        for (Resource r : resources)
            r.setFileName(r.getFileName().substring(0, r.getFileName().trim().lastIndexOf(".")));
        resourceVO.setResources(resources);
        return "search";
    }

    //显示全部
    public String show() {
        List<Resource> resources = resourceService.allResource();
        List<Resource> res = new ArrayList<Resource>();
        for (int i = resources.size() - 1; i >= 0; i--) {
            Resource r = resources.get(i);
            r.setFileName(r.getFileName().substring(0, r.getFileName().trim().lastIndexOf(".")));
            res.add(r);
        }
        resourceVO.setResources(res);
        if (resourceVO.getFlag() == 1) {
            resourceVO.setFlag(0);
            for (Resource r : resources) {
                if (r.getFileName().length() > 15)
                    r.setFileName(r.getFileName().substring(0, 15) + "...");
            }
            resourceVO.setResources(res);
            return "index";
        }
        return "show";
    }

    //显示某个资源
    public String showOne() {
        Resource resource = resourceService.find(Resource.class, Integer.valueOf(resourceVO.getResourceId()));
        resourceVO.setResource(resource);
        HttpSession session = ServletActionContext.getRequest().getSession();
        session.setAttribute("flag", resourceVO.getFlag());
        String valid = null;
        if (resource.getValid() == Valid.WAIT_VALID)
            valid = "等待审核";
        if (resource.getValid() == Valid.PASS_VALID)
            valid = "审核通过";
        if (resource.getValid() == Valid.FAIL_VALID)
            valid = "审核失败";
        session.setAttribute("valid", valid);
        return "showOne";
    }

    //显示用户资源
    public String showPersonResource() {
        HttpSession session = ServletActionContext.getRequest().getSession();
        Person person = (Person) session.getAttribute("person");
        if (person == null) {
            resourceVO.setResultMessage("请登录！");
            return "login";
        }
        List<Resource> resources = resourceService.findResourceByUploader(person.getAccout());
        for (Resource r : resources) {
            r.setFileName(r.getFileName().substring(0, r.getFileName().trim().lastIndexOf(".")));
        }
        resourceVO.setResources(resources);
        return "showPersonResource";
    }

    //删除某个未审核资源
    public String delete() {
        Resource resource = resourceService.find(Resource.class, Integer.valueOf(resourceVO.getResourceId()));
        if (resource.getValid() != Valid.WAIT_VALID) {
            resourceVO.setResultMessage("已审核资源不能删除！");
            return "message";
        } else {
            String user = resource.getUploader();
            String r = resource.getFilePath();
            resourceService.delete(Resource.class, Integer.valueOf(resourceVO.getResourceId()));
            File delFile = new File(resource.getFilePath());
            delFile.delete();
            logger.trace("user:" + user + " delete the resource:" + r);
            return "showPersonResource";
        }
    }

    @Override
    public ResourceVO getModel() {
        return resourceVO;
    }

    @javax.annotation.Resource(name = "resourceServiceImpl")
    public void setResourceService(ResourceService resourceService) {
        this.resourceService = resourceService;
    }
}